#include "fromchknet.h"
#include "ui_fromchknet.h"
#include <QMessageBox>
#include <QComboBox>

fromchknet::fromchknet(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::fromchknet)
{
    ui->setupUi(this);
    this->show();
    //:/ICO/chkNet1.ico
    this->setWindowIcon(QIcon(":/ICO/chkNet1.ico"));
    Start();
}

fromchknet::~fromchknet()
{
    delete ui;
}


QString fromchknet::protocolName(QAbstractSocket::NetworkLayerProtocol protocol)
{
    switch (protocol) {
    case QAbstractSocket::IPv4Protocol:
        return "IPv4 Protocol";
    case QAbstractSocket::IPv6Protocol:
        return "IPv6 Protocol";
    case QAbstractSocket::AnyIPProtocol:
        return "Any IP Protocol";
    default:
        return "Unknown Network Layer Protocol";
    }

}

void fromchknet::Start(){//初始化
    this->setWindowTitle("网络检测工具 1.0 ");

    //读取脚本内容
    QString curPath= QCoreApplication::applicationDirPath();//获取系统当前目录
    QString iniFile=QString("%1/chkScript.txt").arg(curPath);
    QString str=JCode::OpenText(iniFile);
    //str=str.toUpper(); //切换大写
    QStringList list1;
    list1.clear();
    list1<<"别名"<<"类型"<<"CMD/URL"<<"成功字符";
    ui->tableScript->clear();
    ui->tableScript->setColumnCount(list1.size());
    ui->tableScript->setHorizontalHeaderLabels(list1);
    //设置列宽
    ui->tableScript->setColumnWidth(0, 240);
    ui->tableScript->setColumnWidth(1, 80);
    ui->tableScript->setColumnWidth(2, 400);
    ui->tableScript->setColumnWidth(3, 240);

    ui->tableScript->verticalHeader()->setFixedWidth(48);
    ui->tableScript->verticalHeader()->setDefaultSectionSize(48); //设置行距
    ui->tableScript->horizontalHeader()->setFixedHeight(48); //设置表头的高度
    ui->tableScript->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}");
    ui->tableScript->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色
    ui->tableScript->setRowCount(2); //暂时设置成2行
    //ui->tableScript->setEditTriggers(QAbstractItemView::NoEditTriggers); //可编辑
    ui->tableScript->setSelectionMode(QAbstractItemView::ExtendedSelection);//单选
    ui->tableScript->repaint();
    int Tline=-1;
    QStringList strList = str.split("\n");
    for(int i = 0; i < strList.size()-1; i++) {
        QString str1 = strList[i].replace(QRegExp("\\s{1,}"), " ");
        QStringList subList = str1.split("|");
        if (subList.size()>1){
            Tline++;
            if (Tline>=ui->tableScript->rowCount()-1){
                int row = ui->tableScript->rowCount();
                    ui->tableScript->insertRow(row);
            }
            //str1=subList[0].toUpper();
            //list1<<"别名"<<"类型"<<"CMD/URL"<<"成功字符";
           if (subList.size()>0)  ui->tableScript->setItem(Tline,0,new QTableWidgetItem(subList[2].trimmed()));

           if (subList.size()>1)  ui->tableScript->setItem(Tline,1,new QTableWidgetItem(subList[0].trimmed()));
           if (subList.size()>2)  ui->tableScript->setItem(Tline,2,new QTableWidgetItem(subList[1].trimmed()));
           if (subList.size()>3) ui->tableScript->setItem(Tline,3,new QTableWidgetItem(subList[3].trimmed()));
        }
    }


    list1.clear();
    list1<<"名称"<<"状态"<<"检测内容"<<"检测时间"<<"检测结果";
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(list1.size());
    ui->tableWidget->setHorizontalHeaderLabels(list1);
    //设置列宽
    ui->tableWidget->setColumnWidth(0, 240);
    ui->tableWidget->setColumnWidth(1, 80);
    ui->tableWidget->setColumnWidth(2, 400);
    ui->tableWidget->setColumnWidth(3, 240);
    ui->tableWidget->setColumnWidth(4, 660);

    ui->tableWidget->verticalHeader()->setFixedWidth(48);
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(48); //设置行距
    ui->tableWidget->horizontalHeader()->setFixedHeight(48); //设置表头的高度
    ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}");
    ui->tableWidget->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色



    ui->tableWidget->setRowCount(2); //暂时设置成2行
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); //不可编辑
    ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);//单选
    ui->tableWidget->repaint();

    //处理tabWidget

    ui->tabWidget->setTabText(0,"批量检测");
    ui->tabWidget->setTabText(1,"设置批量检测");
    ui->tabWidget->setTabText(2,"IP搜索");
    ui->tabWidget->setTabText(3,"CMD命令行");
    ui->tabWidget->setTabText(4,"网站查阅");
    ui->tabWidget->setTabText(5,"关于");

    ui->tabWidget->setCurrentIndex(0);
    /*ui->tabWidget->setStyleSheet("QTabBar::tab { background: gray; color: white; padding: 10px; } "
                                 "QTabBar::tab:selected { background: black; } " );
                                 */

    QString tabBarStyle = "QTabBar::tab {min-width:100px;color: black;background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 #eeeeee, stop: 1 gray);border: 2px solid;border-top-left-radius: 10px;border-top-right-radius: 10px;padding:5px;}\
    QTabBar::tab:!selected {margin-top: 10px;} \
    QTabBar::tab:selected {color: blue;}";
    ui->tabWidget->setStyleSheet(tabBarStyle);

    QString Tstr=JCode::getUrlString("https://jinesc.cn/JSoft/chkNet.htm");

    ui->txtAbout->setHtml(Tstr);

}


void fromchknet::on_cmdScanIP_clicked()
{
    QString str="";
    for(int i=1;i<255;i++){
        QString ipadd=QString("%1%2").arg(ui->txtIPadd->text()).arg(i);
        QString tmpstr="";
        tmpstr=JCode::PingIP(ipadd);
        qDebug()<<ipadd <<tmpstr;
        str=QString("Ping %1 >> %2\n%3").arg(ipadd).arg(tmpstr).arg(str);

        ui->txtJG->setText(str);
        ui->txtJG->repaint();  //因为setText()不会立即调用paintEvent进行绘图。程序会等你退出循环后才有机会进行绘图。
        //解决的办法是：        label->setText()后，调用label->repaint()立即重绘。
    }
    ui->txtJG->setText(str);
}


void fromchknet::on_cmdScriptStart_clicked()
{
    QStringList list1;
    list1.clear();
    list1<<"名称"<<"状态"<<"检测内容"<<"检测时间"<<"检测结果";
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(list1.size());
    ui->tableWidget->setHorizontalHeaderLabels(list1);
    //设置列宽
    ui->tableWidget->setColumnWidth(0, 200);
    ui->tableWidget->setColumnWidth(1, 80);
    ui->tableWidget->setColumnWidth(2, 360);
    ui->tableWidget->setColumnWidth(3, 200);
    ui->tableWidget->setColumnWidth(4, 500);

    ui->tableWidget->verticalHeader()->setFixedWidth(48);
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(48); //设置行距
    ui->tableWidget->horizontalHeader()->setFixedHeight(48); //设置表头的高度
    ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}");
    ui->tableWidget->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色
    ui->tableWidget->setRowCount(2); //暂时设置成2行
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); //不可编辑
    ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);//单选
    ui->tableWidget->repaint();

    //ui->tableWidget->horizontalScrollBar()->setEnabled(false);
    int  Tline=-1; //行号

    QString str="";
    for(int i=0;i<ui->tableScript->rowCount();i++){
        if(ui->tableScript->item(i,0)!=NULL && ui->tableScript->item(i,0)->text().trimmed()!="" ){
            //list1<<"别名"<<"类型"<<"CMD/URL"<<"成功字符";
            if (ui->tableScript->item(i,1)!=NULL) str+=ui->tableScript->item(i,1)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,2)!=NULL) str+=ui->tableScript->item(i,2)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,0)!=NULL) str+=ui->tableScript->item(i,0)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,3)!=NULL) str+=ui->tableScript->item(i,3)->text().trimmed();
            str+="\n";
        }
    }
    QStringList strList = str.split("\n");
    for(int i = 0; i < strList.size()-1; i++) {
        QString str1 = strList[i].replace(QRegExp("\\s{1,}"), " ");
        QStringList subList = str1.split("|");
        if (subList.size()>1){
            Tline++;
            if (Tline>=ui->tableWidget->rowCount()-1){
                int row = ui->tableWidget->rowCount();
                    ui->tableWidget->insertRow(row);
            }
            str1=subList[0].toUpper();            
            if (str1=="CMD"){

                //list1<<"名称"<<"状态"<<"检测内容"<<"检测结果";
                str=subList[2].trimmed();
                ui->tableWidget->setItem(Tline,0,new QTableWidgetItem(str));
                str="";
                ui->tableWidget->setItem(Tline,1,new QTableWidgetItem(str));
                str=QString("%1-%2").arg(subList[0]).arg(subList[1]);
                ui->tableWidget->setItem(Tline,2,new QTableWidgetItem(str));
                QDateTime current_date_time =QDateTime::currentDateTime();
                str=current_date_time.toString("yyyy年MM月dd日 hh:mm:ss.zzz ddd");
                ui->tableWidget->setItem(Tline,3,new QTableWidgetItem(str));
                str=JCode::CMD(subList[1]).trimmed();
                ui->tableWidget->setItem(Tline,4,new QTableWidgetItem(str));
                //设置红绿灯
                QWidget *pWidget = new QWidget();
                QHBoxLayout *pLayout = new QHBoxLayout();
                pLayout->setMargin(0);
                QLabel *pLabel = new QLabel();
                setLED(pLabel, 1, 16); //把红绿灯变成红色了
                QLabel *pLabel1 = new QLabel();

                pLabel1->setText("异常");

                pLayout->addWidget(pLabel);
                //pLayout->addWidget(pLabel1);
                pLayout->setAlignment(Qt::AlignLeft);
                if (str.contains(subList[3].trimmed(),Qt::CaseSensitive)){
                    setLED(pLabel, 2, 16); //把红绿灯变成绿色了
                    pLabel1->setText("正常");
                }
                pWidget->setLayout(pLayout);
                pWidget->resize(ui->tableWidget->columnWidth(1),48);
                pWidget->setStyleSheet("QWidget{ border: 0px }");
                ui->tableWidget->setCellWidget(Tline,1,pWidget);
                ui->tableWidget->item(Tline,1)->setText(QString("%1").arg(pLabel1->text()));
                ui->tableWidget->item(Tline,1)->setTextAlignment(Qt::AlignCenter);

                ui->tableWidget->repaint();

            }
            if (str1=="URL"){
                QString Tstr=JCode::getUrlString(subList[1]);
                str=subList[2].trimmed();
                ui->tableWidget->setItem(Tline,0,new QTableWidgetItem(str));
                str="";
                ui->tableWidget->setItem(Tline,1,new QTableWidgetItem(str));
                str=QString("%1-%2").arg(subList[0]).arg(subList[1]);
                ui->tableWidget->setItem(Tline,2,new QTableWidgetItem(str));
                QDateTime current_date_time =QDateTime::currentDateTime();
                str=current_date_time.toString("yyyy年MM月dd日 hh:mm:ss.zzz ddd");
                ui->tableWidget->setItem(Tline,3,new QTableWidgetItem(str));
                str=Tstr;
                ui->tableWidget->setItem(Tline,4,new QTableWidgetItem(str));
                //设置红绿灯
                QWidget *pWidget = new QWidget();
                QHBoxLayout *pLayout = new QHBoxLayout();
                pLayout->setMargin(0);
                QLabel *pLabel = new QLabel();
                setLED(pLabel, 0, 16); //把红绿灯变成灰色了
                QLabel *pLabel1 = new QLabel();

                pLabel1->setText("待检测");
                pLayout->addWidget(pLabel);
                //pLayout->addWidget(pLabel1);
                pLayout->setAlignment(Qt::AlignLeft);

                if (subList.size()>2){
                    if (Tstr.contains(subList[3].trimmed(),Qt::CaseSensitive)){
                        setLED(pLabel, 2, 16); //把红绿灯变成绿色了
                        pLabel1->setText("正常");

                    }else{

                        setLED(pLabel, 1, 16); //把红绿灯变成红色了
                        pLabel1->setText("异常");
                    }
                    //tmpstr+=QString(" >>>  %2k  %1 \n").arg(Tstr.replace("\n","")).arg(Tstr.length()/1024);
                }
                pWidget->setLayout(pLayout);
                pWidget->resize(ui->tableWidget->columnWidth(1),48);
                pWidget->setStyleSheet("QWidget{ border: 0px }");
                ui->tableWidget->setCellWidget(Tline,1,pWidget);
                ui->tableWidget->item(Tline,1)->setText(QString("%1").arg(pLabel1->text()));
                ui->tableWidget->item(Tline,1)->setTextAlignment(Qt::AlignCenter);

                ui->tableWidget->repaint();
            }
        }


    }
}
void fromchknet::setLED(QLabel* label, int color, int size)
{
    // 该函数将label控件变成一个圆形指示灯，需要指定颜色color以及直径size
    // color 0:grey 1:red 2:green 3:yellow
    // size  单位是像素
    // 将label中的文字清空
    label->setText("");
    // 先设置矩形大小
    // 如果ui界面设置的label大小比最小宽度和高度小，矩形将被设置为最小宽度和最小高度；
    // 如果ui界面设置的label大小比最小宽度和高度大，矩形将被设置为最大宽度和最大高度；
    QString min_width = QString("min-width: %1px;").arg(size);              // 最小宽度：size
    QString min_height = QString("min-height: %1px;").arg(size);            // 最小高度：size
    QString max_width = QString("max-width: %1px;").arg(size);              // 最小宽度：size
    QString max_height = QString("max-height: %1px;").arg(size);            // 最小高度：size
    // 再设置边界形状及边框
    QString border_radius = QString("border-radius: %1px;").arg(size/2);    // 边框是圆角，半径为size/2
    QString border = QString("border:1px solid black;");                    // 边框为1px黑色
    // 最后设置背景颜色
    QString background = "background-color:";
    switch (color) {
    case 0:        // 灰色
        background += "rgb(190,190,190)";
        break;
    case 1:        // 红色
        background += "rgb(255,0,0)";
        break;
    case 2:        // 绿色
        background += "rgb(0,255,0)";
        break;
    case 3:        // 黄色
        background += "rgb(255,255,0)";
        break;
    default:
        break;
    }
    const QString SheetStyle = min_width + min_height + max_width + max_height + border_radius + border + background;
    label->setStyleSheet(SheetStyle);
}

void fromchknet::on_cmdCMD_clicked()
{
    QString str=ui->txtCMD->toPlainText();
    QString outStr="";
    str+="\n";
    QStringList strList = str.split("\n");
    for(int i = 0; i < strList.size()-1; i++) {
        if (strList[i].trimmed()!=""){
            outStr+=strList[i].trimmed()+"\n";
            outStr+="-------------------------------------------------\n";
            outStr+=JCode::CMD(strList[i].trimmed());
            outStr+="\n";
        }
    }
    //QString str=JCode::CMD(ui->txtCMD->text()).trimmed();
    ui->textCMD->setText(outStr);
}

void fromchknet::on_cmdUrl_clicked()
{
    QString Tstr=JCode::getUrlString(ui->txtUrl->text());

    ui->txtUrlTxt->setPlainText(Tstr);
    ui->txtUrlHtml->setHtml(Tstr);
}



void fromchknet::on_cmdSet_SaveScript_clicked()
{
    QString str="";
    for(int i=0;i<ui->tableScript->rowCount();i++){
        if(ui->tableScript->item(i,0)!=NULL && ui->tableScript->item(i,0)->text().trimmed()!="" ){
            //list1<<"别名"<<"类型"<<"CMD/URL"<<"成功字符";
            if (ui->tableScript->item(i,1)!=NULL) str+=ui->tableScript->item(i,1)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,2)!=NULL) str+=ui->tableScript->item(i,2)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,0)!=NULL) str+=ui->tableScript->item(i,0)->text().trimmed();
            str+="|";
            if (ui->tableScript->item(i,3)!=NULL) str+=ui->tableScript->item(i,3)->text().trimmed();
            str+="\n";
        }
    }
    //QMessageBox::information(this,"提示信息",str);
    QString curPath=QCoreApplication::applicationDirPath();//获取系统当前目录;//获取系统当前目录
    QString iniFile=QString("%1/chkScript.txt").arg(curPath);
    if (JCode::SaveText(iniFile,str)==false){
        QMessageBox::warning(this,"警告","文件保存失败！");
    }else{
        QMessageBox::information(this,"提示信息","文件保存成功！");
    }
}

void fromchknet::on_cmdScriptInsLine_clicked()
{
    int curRow = ui->tableScript->currentRow();
    if(curRow != ui->tableScript->rowCount()){
    //当不是最后一行时
        if(curRow == ui->tableScript->rowCount() - 1){
        //若为倒数第二行
            ui->tableScript->insertRow(curRow + 1);
            //在其下添加一行，即在最后一行上添加一行，但最后一行进行操作时是在末尾添加，因此先在末尾添加一行，使原来的最后一行变为倒数第二行，在该行基础上添加一行即在原来倒数第二行下；然后再删去末尾多添加的一行
            ui->tableScript->insertRow(curRow + 1);
            ui->tableScript->removeRow(curRow + 3);

        }
        else{
        //若为其他行
            ui->tableScript->insertRow(curRow + 1);

        }
    }
    else{
    //当为最后一行时
        ui->tableScript->insertRow(curRow);

    }

}


void fromchknet::on_cmdScriptDelLine_clicked()
{
    int curRow = ui->tableScript->currentRow();
    if (curRow != -1) ui->tableScript->removeRow(curRow);
}



void fromchknet::on_cmdScripCopy_clicked()
{
    JCode::FZTableWidget(ui->tableWidget);
}
